package com.itcast.jdbc;

import com.itcast.util.jdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 事务操作
 */
public class jdbcDemo10 {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement ps1 = null;
        PreparedStatement ps2 = null;

        try {
            // 1.获取连接对象
            connection = jdbcUtils.getConnection();
            // 开启事务
            connection.setAutoCommit(false);

            // 2.定义 sql
            // 2.1张三 -500
            String sql1 = "UPDATE account SET balance = balance - ? WHERE id = ?";
            // 2.2李四 +500
            String sql2 = "UPDATE account SET balance = balance + ? WHERE id = ?";
            // 3.获取执行 sql 对象
            ps1 = connection.prepareStatement(sql1);
            ps2 = connection.prepareStatement(sql2);
            // 4.赋值
            ps1.setDouble(1, 500);
            ps1.setInt(2, 1);
            ps2.setDouble(1, 500);
            ps2.setInt(2, 2);
            // 5.执行 sql
            int count1 = ps1.executeUpdate();
            // 手动创造异常
            int i = 3 / 0;

            int count2 = ps2.executeUpdate();

            // 提交事务
            connection.commit();

        } catch (Exception e) {
            // 事务回滚
            if (connection != null) {
                try {
                    connection.rollback();
                } catch (SQLException ex) {
                    e.printStackTrace();
                }
            }
            e.printStackTrace();
        } finally {
            jdbcUtils.close(ps1, connection);
            jdbcUtils.close(ps2, null);
        }

    }
}
